package com.shop.interceptor;

import com.shop.constant.JwtClaimsConstant;
import com.shop.properties.JwtProperties;
import com.shop.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenAdminInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 校验jwt
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        // 打印获取 JWT 之前的日志
        log.info("尝试从请求头中获取 JWT，请求头中 JWT 的名称为: {}", jwtProperties.getAdminTokenName());

        //1、从请求头中获取令牌
        String token = request.getHeader(jwtProperties.getAdminTokenName());

        // 打印获取 JWT 之后的日志
        if (token != null) {
            log.info("成功从请求头中获取到 JWT: {}", token);
        } else {
            log.info("未从请求头中获取到 JWT");
        }

        //2、校验令牌
        try {
            log.info("开始校验 JWT，使用的密钥: {}", jwtProperties.getAdminSecretKey());
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
            log.info("Token 原始内容: {}", claims);

            // 检查过期时间
            Date expiration = claims.getExpiration();
            log.info("Token 过期时间: {}", expiration);
            if (expiration.before(new Date())) {
                log.error("Token 已过期");
            }

            Long empId = Long.valueOf(claims.get(JwtClaimsConstant.EMP_ID).toString());
            log.info("当前员工id：{}", empId);
            return true;
        } catch (Exception ex) {
            log.error("JWT 校验失败，详细原因:", ex); // 打印完整堆栈
            response.setStatus(401);
            return false;
        }
    }
}